<template>
    <div>
        <el-breadcrumb
            separator-class="el-icon-arrow-right"
            class="breadcrumb-base"
            style="line-height: 30px;"
        >
            <el-breadcrumb-item>
                <i class="el-icon-edit-outline"></i>
                医嘱项目
            </el-breadcrumb-item>
        </el-breadcrumb>

        <div class="main-container">
            <el-row>
                <!--ss: 1 特殊染色, mo: 2 分子病理, ihc: 3 免疫组化, tech: 4 技术医嘱-->
                <el-tabs
                    v-model="typeActiveTab"
                    @tab-click="typeActiveTabClick"
                    type="card"
                >
                    <el-tab-pane
                        v-for="advice in doctorAdviceMap"
                        :key="advice.type"
                        :name="advice.key"
                        :label="advice.label"
                    >
                    </el-tab-pane>
                </el-tabs>
            </el-row>
            <el-row>
                <el-switch
                    v-if="isWithPackage"
                    v-model="isShowPackage"
                    @change="adviceTableInit"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    inactive-text="显示套餐"
                >
                </el-switch>

                <el-input
                    v-if="!isTechAdvice"
                    v-model="searchKey"
                    placeholder="请输入名称"
                    class="input-form"
                    size="mini"
                >
                </el-input>
                <el-button
                    v-if="!isTechAdvice"
                    @click="searchByName"
                    type="primary"
                    size="mini"
                >
                    搜索
                </el-button>

                <el-button
                    v-if="isShowPackage"
                    @click="packageDialogOpen(-1)"
                    type="primary"
                    size="mini"
                    style="float: right"
                >
                    新增套餐
                </el-button>
                <el-button
                    v-if="!isTechAdvice && !isShowPackage"
                    @click="adviceDialogOpen(-1)"
                    type="primary"
                    size="mini"
                    style="float: right"
                >
                    新增单项
                </el-button>
            </el-row>
            <el-row style="margin-top: 10px;">
                <base-table
                    class="data-table-style"
                    ref="adviceTable"
                    v-loading="adviceTable.isLoading"
                    :data="adviceTable.data"
                    :header="adviceTable.header"
                    :operation="adviceTable.operation"
                    :pageInfo="adviceTable.pageInfo"
                    :selected="false"
                    @handleClick="adviceTableButtonClick"
                    @pageJumpTo="adviceTablePageJumpTo"
                    @sizeChange="adviceTableSizeChange"
                >
                </base-table>
            </el-row>
        </div>

        <el-dialog
            :title="adviceDialog.title"
            :visible.sync="adviceDialog.visible"
            :close-on-click-modal="false"
            :modal-append-to-body="false"
            append-to-body
            width="25%"
        >
            <el-form
                ref="adviceForm"
                label-width="150px"
                :model="adviceForm"
                :rules="adviceFormRules"
            >
                <el-form-item
                    label="医嘱项目名称"
                    prop="name"
                    class="label-padding-bottom"
                >
                    <el-input
                        v-model="adviceForm.name"
                        placeholder="请输入医嘱项目名称"
                        class="input-form"
                        size="mini"
                        maxlength="255"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="医嘱项目价格"
                    prop="cost"
                    class="label-padding-bottom"
                >
                    <el-input
                        v-model="adviceForm.cost"
                        placeholder="请输入医嘱项目价格"
                        class="input-form"
                        size="mini"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="备注"
                    class="label-padding-bottom"
                >
                    <el-input
                        v-model="adviceForm.remark"
                        placeholder="请输入备注"
                        class="input-form"
                        size="mini"
                        maxlength="255"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="HIS连接码"
                    class="label-padding-bottom"
                >
                    <el-input
                        v-model="adviceForm.hisCode"
                        placeholder="请输入HIS连接码"
                        class="input-form"
                        size="mini"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="备注一"
                    class="label-padding-bottom"
                >
                    <el-input
                        v-model="adviceForm.remarkOne"
                        placeholder="请输入备注一"
                        class="input-form"
                        size="mini"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="备注二"
                    class="label-padding-bottom"
                >
                    <el-input
                        v-model="adviceForm.remarkTwo"
                        placeholder="请输入备注二"
                        class="input-form"
                        size="mini"
                    ></el-input>
                </el-form-item>
            </el-form>

            <span
                slot="footer"
                class="dialog-footer"
                style="text-align: right;"
            >
                <el-button
                    :loading="commitLoading"
                    @click="adviceDialogCommit"
                    type="primary"
                    size="mini"
                >提交</el-button>
                <el-button
                    @click="adviceDialog.visible = false"
                    size="mini"
                >关闭</el-button>
            </span>
        </el-dialog>
        <el-dialog
            :title="packageDialog.title"
            :visible.sync="packageDialog.visible"
            :close-on-click-modal="false"
            :modal-append-to-body="false"
            append-to-body
            width="65%"
        >
            <el-form
                ref="packageForm"
                label-width="80px"
                :inline="true"
                :model="packageForm"
                :rules="packageFormRules"
            >
                <el-form-item
                    label="套餐名称"
                    prop="name"
                    class="label-padding-bottom"
                >
                    <el-input
                        v-model="packageForm.name"
                        placeholder="请输入套餐名称"
                        class="input-form"
                        size="mini"
                        maxlength="100"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="套餐说明"
                    class="label-padding-bottom"
                >
                    <el-input
                        v-model="packageForm.remark"
                        placeholder="请输入套餐说明"
                        class="input-form"
                        size="mini"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="折扣"
                    class="label-padding-bottom"
                >
                    <el-input
                        v-model="packageForm.discount"
                        placeholder="请输入折扣"
                        class="input-form"
                        size="mini"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="医嘱单项"
                    class="label-padding-bottom"
                >
                    <div style="width: 300px;">
                        <el-select
                            v-model="packageDialog.adviceSelected"
                            placeholder="请选择医嘱单项"
                            multiple
                            filterable
                            remote
                            size="mini"
                            class="picker-form"
                        >
                            <el-option
                                v-for="data in packageDialog.advicesAll"
                                :key="data.id"
                                :label="data.name"
                                :value="data.id"
                            >
                            </el-option>
                        </el-select>
                        <el-button
                            @click="adviceSelectAdd"
                            type="primary"
                            size="mini"
                        >添加
                        </el-button>
                    </div>
                </el-form-item>
            </el-form>
            <el-row style="margin-top: 10px;">
                <base-table
                    ref="packageDialogTable"
                    :data="packageDialogTable.data"
                    :header="packageDialogTable.header"
                    :operation="packageDialogTable.operation"
                    :pageInfo="packageDialogTable.pageInfo"
                    :selected="false"
                    @handleClick="packageDialogTableButtonClick"
                    @pageJumpTo="packageDialogTablePageJumpTo"
                    @sizeChange="packageDialogTableSizeChange"
                >
                </base-table>
            </el-row>
            <span
                slot="footer"
                class="dialog-footer"
                style="text-align: right;"
            >
                <el-button
                    @click="packageDialogCommit"
                    type="primary"
                    size="mini"
                    :loading="commitLoading"
                >提交</el-button>
                <el-button
                    @click="packageDialog.visible = false"
                    size="mini"
                >关闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import BaseTable from '@templates/components/BaseTable';
import _ from 'lodash';
import { itemsPerPage } from '@/client/libs/util';
import { vxRule } from '@/client/libs/validator';

const doctorAdviceMapBase = [
    {
        key: 'ss',
        type: 1,
        label: '特殊染色',
        isWithPackage: false,
    },
    {
        key: 'mo',
        type: 2,
        label: '分子病理',
        isWithPackage: true,
    },
    {
        key: 'ihc',
        type: 3,
        label: '免疫组化',
        isWithPackage: true,
    },
    {
        key: 'tech',
        type: 4,
        label: '技术医嘱',
        isWithPackage: false,
    },
];
const adviceTableBase = {
    header: [
        {
            label: '项目名称',
            prop: 'name',
            width: '160',
        },
        {
            label: '项目价格',
            prop: 'cost',
            width: '160',
        },
        {
            label: '项目说明',
            prop: 'remark',
        },
        {
            label: 'HIS关联码',
            prop: 'hisCode',
        },
        {
            label: '备注一',
            prop: 'remarkOne',
        },
        {
            label: '备注二',
            prop: 'remarkTwo',
        },
    ],
    operation: [
        {
            label: '编辑',
            functionKey: 'adviceTableAdviceEdit',
        },
        {
            label: '删除',
            color: 'red',
            functionKey: 'adviceTableDelete',
        },
    ],
};
const packageTableBase = {
    header: [
        {
            label: '套餐名称',
            prop: 'name',
            width: '200',
        },
        {
            label: '套餐折扣',
            prop: 'discount',
            width: '200',
        },
        {
            label: '套餐说明',
            prop: 'remark',
        },
    ],
    operation: [
        {
            label: '编辑',
            functionKey: 'adviceTablePackageEdit',
        },
        {
            label: '删除',
            color: 'red',
            functionKey: 'adviceTableDelete',
        },
    ],
};
export default {
    name: 'InstitutionDoctorAdvices',
    components: {
        BaseTable,
    },
    data() {
        const checkName = (rule, value, callback) => {
            if (!value) {
                callback(new Error(' '));
                this.$message.warning('请填写套餐名称');
            } else {
                callback();
            }
        };
        return {
            commitLoading: false,
            state: this.$store.state,
            typeActiveTab: 'ss',
            // 是否显示套餐
            isShowPackage: false,

            searchKey: '',

            doctorAdviceMap: doctorAdviceMapBase,

            adviceTable: {
                isLoading: true,
                data: [],
                header: [],
                operation: [],
                pageInfo: {
                    page: 1,
                    size: itemsPerPage.get(),
                    total: 0,
                },
            },

            adviceDialog: {
                visible: false,
                title: '',
                commitMethod: '',
            },
            adviceForm: {
                name: '',
                cost: '',
                remark: '',
                hisCode: '',
                remarkOne: '',
                remarkTwo: '',
            },
            adviceFormRules: {
                name: [vxRule(true, null, 'blur', '请填写医嘱项目名称')],
                cost: [vxRule(true, 'int', 'blur', '请输入数字')],
            },

            packageDialog: {
                visible: false,
                title: '',
                commitMethod: '',

                adviceSelected: [],
                advicesAll: [],
                tableDataAll: [],
            },
            packageDialogTable: {
                data: [],
                header: [
                    {
                        label: '项目名称',
                        prop: 'name',
                        width: '160',
                    },
                    {
                        label: '项目价格',
                        prop: 'cost',
                        width: '160',
                    },
                    {
                        label: '项目说明',
                        prop: 'remark',
                    },
                    {
                        label: 'HIS关联码',
                        prop: 'hisCode',
                    },
                    {
                        label: '备注一',
                        prop: 'remarkOne',
                    },
                    {
                        label: '备注二',
                        prop: 'remarkTwo',
                    },
                ],
                operation: [
                    {
                        label: '删除',
                        color: 'red',
                        functionKey: 'packageDialogTableDelete',
                    },
                ],
                pageInfo: {
                    page: 1,
                    size: itemsPerPage.get(),
                    total: 0,
                },
            },
            packageForm: {
                name: '',
                remark: '',
                discount: '',
                adviceList: [],
            },
            packageFormRules: {
                name: [
                    {
                        required: true,
                        message: ' ',
                        validator: checkName,
                        trigger: 'blur',
                    },
                ],
            },
        };
    },
    mounted() {
        this.adviceTableInit();
    },
    computed: {
        typeActiveItem() {
            return this.doctorAdviceMap.find(
                (t) => t.key === this.typeActiveTab
            );
        },
        // 请求接口相关数据
        requestInterface() {
            return this.isShowPackage
                ? '/doctor-advice-packages'
                : '/doctor-advices';
        },

        isWithPackage() {
            return this.typeActiveItem.isWithPackage;
        },
        isTechAdvice() {
            return this.typeActiveItem.key === 'tech';
        },
    },
    methods: {
        adviceTableInit() {
            this.adviceTable.isLoading = true;
            const baseTable = {
                isLoading: true,
                data: [],
                header: [],
                operation: [],
                pageInfo: {
                    page: 1,
                    size: itemsPerPage.get(),
                    total: 0,
                },
            };

            if (this.isShowPackage) {
                baseTable.header = _.clone(packageTableBase.header);
                baseTable.operation = _.clone(packageTableBase.operation);
            } else {
                baseTable.header = _.clone(adviceTableBase.header);
                baseTable.operation = _.clone(adviceTableBase.operation);
            }

            this.adviceTable = baseTable;
            this.adviceTableDataRequest();
        },
        async adviceTableDataRequest() {
            const res = await this.$axios({
                method: 'GET',
                url: `/PROXY-Remote${this.requestInterface}`,
                params: {
                    name: this.searchKey,
                    type: this.typeActiveItem.type,
                    size: this.adviceTable.pageInfo.size,
                    page: this.adviceTable.pageInfo.page - 1,
                },
            });

            if (res && res.data.code === 200) {
                const result = res.data;
                this.adviceTable.pageInfo = {
                    hide: this.isTechAdvice,
                    total: result.pageInfo.total,
                    page: result.pageInfo.page + 1,
                    size: result.pageInfo.size,
                };
                this.adviceTable.data = [];
                result.data.forEach((t, index) => {
                    const item = t;
                    item.index = index;
                    this.adviceTable.data.push(item);
                });
            }
            this.adviceTable.isLoading = false;
        },
        typeActiveTabClick() {
            this.isShowPackage = false;
            this.searchKey = '';
            this.adviceTableInit();
        },
        searchByName() {
            this.adviceTable.pageInfo.page = 1;
            this.adviceTableDataRequest();
        },
        adviceTableButtonClick(functionKey, row) {
            this[functionKey](row);
        },
        adviceTablePageJumpTo(val) {
            this.adviceTable.pageInfo.page = val;
            // 为 adviceTable.data 赋值相应页上新数据
            this.adviceTableDataRequest();
        },
        adviceTableSizeChange(val) {
            this.adviceTable.pageInfo.size = val;
            this.adviceTable.pageInfo.page = 1;
            // 为 adviceTable.data 赋值相应数据量新数据
            this.adviceTableDataRequest();
        },
        adviceTableAdviceEdit(row) {
            this.adviceDialogOpen(row.index);
        },
        adviceTablePackageEdit(row) {
            this.packageDialogOpen(row.index);
        },
        adviceTableDelete(row) {
            if (this.isTechAdvice) {
                this.$message.info('此医嘱不能删除');
            } else {
                const messageFlag = !this.isShowPackage ? '项目' : '套餐';
                this.$confirm(`删除该${messageFlag}, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                })
                    .then(async () => {
                        try {
                            await this.$axios({
                                // 详见 axios 请求配置项
                                method: 'DELETE',
                                url: `/PROXY-Remote${this.requestInterface}/${row.id}`,
                            }).then((res) => {
                                // 请求失败
                                if (res.data.code !== 200) {
                                    throw new Error(res.data);
                                }

                                // 请求成功
                                this.$message.success('删除成功!');
                                if (this.adviceTable.data.length === 1) {
                                    if (this.adviceTable.pageInfo.page > 1) {
                                        this.adviceTable.pageInfo.page -= 1;
                                    }
                                }
                                this.adviceTableDataRequest();
                            });
                        } catch (e) {
                            // 跳出
                        }
                    })
                    .catch(() => {});
            }
        },

        // adviceDialog
        adviceDialogOpen(index) {
            this.adviceForm = {
                id: 0,
                name: '',
                cost: '0',
                remark: '',
                hisCode: '',
                remarkOne: '',
                remarkTwo: '',
                institutionId: this.state.institution.id,
                type: this.typeActiveItem.type,
            };
            if (index < 0) {
                this.adviceDialog.commitMethod = 'POST';
                this.adviceDialog.title = '新增项目';

                delete this.adviceForm.id;
            } else {
                Object.keys(this.adviceForm).forEach((key) => {
                    this.adviceForm[key] = this.adviceTable.data[index][key];
                });
                this.adviceDialog.commitMethod = 'PUT';
                this.adviceDialog.title = '编辑项目';
            }

            this.adviceDialog.visible = true;
        },
        adviceDialogCommit() {
            this.$refs.adviceForm.validate(async (valid) => {
                if (valid) {
                    this.commitLoading = true;
                    await this.$axios({
                        // 详见 axios 请求配置项
                        method: this.adviceDialog.commitMethod,
                        url: `/PROXY-Remote${this.requestInterface}`,
                        data: this.adviceForm,
                    }).then((res) => {
                        // 请求失败
                        if (res.data.code !== 200) {
                            throw new Error(res.data);
                        }

                        // 请求成功
                        this.$message.success(`${this.adviceDialog.title}成功`);
                        this.adviceDialog.visible = false;
                        this.adviceTableDataRequest();
                        this.commitLoading = false;
                    });
                }
            });
        },
        packageDialogOpen(index) {
            this.packageDialogTable.data = [];
            this.packageForm = {
                id: 0,
                name: '',
                discount: '0',
                remark: '',
                institutionId: this.state.institution.id,
                type: this.typeActiveItem.type,
            };
            if (index < 0) {
                this.packageDialog.commitMethod = 'POST';
                this.packageDialog.title = '新增套餐';

                this.packageDialog.adviceTableDataAll = [];
                delete this.packageForm.id;
            } else {
                Object.keys(this.packageForm).forEach((key) => {
                    this.packageForm[key] = this.adviceTable.data[index][key];
                });
                this.packageDialog.commitMethod = 'PUT';
                this.packageDialog.title = '编辑套餐';

                const adviceList =
                    this.adviceTable.data[index].doctorAdviceList;
                this.packageDialog.adviceTableDataAll = _.clone(adviceList);
            }

            this.packageDialogTableRequest();
            this.packageDialogAdvicesAllRequest();
            this.packageDialog.visible = true;
        },
        packageDialogCommit() {
            this.$refs.packageForm.validate(async (valid) => {
                if (valid) {
                    this.packageForm.doctorAdviceList = [];
                    this.packageDialog.adviceTableDataAll.forEach((t) => {
                        this.packageForm.doctorAdviceList.push({
                            id: t.id,
                        });
                    });
                    this.commitLoading = true;
                    this.$axios({
                        // 详见 axios 请求配置项
                        method: this.packageDialog.commitMethod,
                        url: `/PROXY-Remote${this.requestInterface}`,
                        data: this.packageForm,
                    }).then((res) => {
                        // 请求失败
                        if (res.data.code !== 200) {
                            throw new Error(res.data);
                        }

                        // 请求成功
                        this.$message.success(
                            `${this.packageDialog.title}成功`
                        );
                        this.packageDialog.visible = false;
                        this.adviceTableDataRequest();
                        this.commitLoading = false;
                    });
                }
            });
        },
        packageDialogTableRequest() {
            this.packageDialogTable.pageInfo.total =
                this.packageDialog.adviceTableDataAll.length;

            const { page } = this.packageDialogTable.pageInfo;
            const { size } = this.packageDialogTable.pageInfo;
            const { total } = this.packageDialogTable.pageInfo;

            this.packageDialogTable.data = [];
            for (let i = (page - 1) * size; i < total && i < page * size; i++) {
                this.packageDialogTable.data.push(
                    this.packageDialog.adviceTableDataAll[i]
                );
            }
        },
        async packageDialogAdvicesAllRequest() {
            try {
                await this.$axios({
                    method: 'GET',
                    url: '/PROXY-Remote/doctor-advices',
                    params: {
                        type: this.typeActiveItem.type,
                    },
                }).then((res) => {
                    // 请求失败
                    if (res.data.code !== 200) {
                        throw new Error(res.data);
                    }

                    // 请求成功
                    const result = res.data;
                    this.packageDialog.advicesAll = _.clone(result.data);
                });
            } catch (e) {
                // 跳出
            }
        },
        adviceSelectAdd() {
            this.packageDialog.adviceSelected.forEach((id) => {
                // 判重
                const isRepeat = this.packageDialog.adviceTableDataAll.some(
                    (t) => t.id === id
                );
                if (isRepeat) {
                    this.$message.warning('重复添加');
                    return;
                }
                // 选择框数据为 id ，需要将完整数据添加进表格
                const advice = this.packageDialog.advicesAll.find(
                    (t) => t.id === id
                );
                this.packageDialog.adviceTableDataAll.push(advice);
                this.$message.success('添加成功');
                // 依照 id 顺序排列
                this.packageDialog.adviceTableDataAll.sort(
                    (a, b) => a.id - b.id
                );
            });
            this.packageDialog.adviceSelected = [];
            this.packageDialogTableRequest();
        },
        packageDialogTableButtonClick(functionKey, row) {
            this[functionKey](row);
        },
        packageDialogTablePageJumpTo(val) {
            this.packageDialogTable.pageInfo.page = val;
            // 为 adviceTable.data 赋值相应页上新数据
            this.packageDialogTableRequest();
        },
        packageDialogTableSizeChange(val) {
            this.packageDialogTable.pageInfo.size = val;
            this.packageDialogTable.pageInfo.page = 1;
            // 为 adviceTable.data 赋值相应数据量新数据
            this.packageDialogTableRequest();
        },
        packageDialogTableDelete(row) {
            let deleteID = -1;
            this.packageDialog.adviceTableDataAll.forEach((t, index) => {
                if (t.id === row.id) {
                    deleteID = index;
                }
            });
            if (deleteID >= 0) {
                this.packageDialog.adviceTableDataAll.splice(deleteID, 1);
                this.$message.success('删除成功');
                this.packageDialogTableRequest();
            }
        },
    },
};
</script>

<style scoped>
.label-padding-bottom {
    padding-top: 0;
    padding-bottom: 12px;
}

.data-table-style >>> .el-table__fixed-body-wrapper {
    top: 40px !important;
}
</style>
